/*
 * @Descripttion:
 * @version:
 * @Author: ChenXiang
 * @Date: 2021-08-01 16:54:44
 * @LastEditors: ChenXiang
 * @LastEditTime: 2021-08-07 21:10:12
 */

import React from "react";
import { RouterContext } from "./Context";
export default class Router extends React.Component {
  static computeRootMatch(pathname) {
    return { path: "/", url: "/", params: {}, isExact: pathname === "/" };
  }
  constructor(props) {
    super(props);
    this.state = {
      location: props.history.location,
    };
    // location 发生变化，要执行这里
    this.unlisten = props.history.listen((location) => {
      this.setState({ location });
    });
  }

  componentWillUnmount() {
    // TODO 不懂待实践
    if (this.unlisten) {
      this.unlisten();
    }
  }

  render() {
    return (
      <RouterContext.Provider
        value={{
          history: this.props.history,
          location: this.state.location,
          match: Router.computeRootMatch(this.state.location.pathname),
        }}
      >
        {this.props.children}
      </RouterContext.Provider>
    );
  }
}
